<template>
  <div>
    <div class="head-container">
      <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
    </div>
    <div class="head-container">
      <el-tree class="treeStyle" node-key="id" :current-node-key="currentNodeKey" :highlight-current="true" :data="deptOptions" :props="defaultProps" default-expand-all :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" @node-click="handleNodeClick" />
    </div>
  </div>
</template>

<script>
import { treeselect } from "@/api/system/dept";

export default {
  model: {
    prop: "value",
    event: "change"
  },
  data() {
    return {
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
    }
  },
  props: {
    value: {
      type: [String, Number],
      default: void 0
    },
  },
  created() {
    this.getTreeselect();
  },
  computed: {
    currentNodeKey: {
      get() {
        return this.value
      },
      set(value) {
        console.log("currentNodeKey", value)
      }
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
        let defaultDeptId = this.getFirstLeafNode(this.deptOptions).id;
        this.$emit("change", defaultDeptId);
        this.$emit("select", defaultDeptId);
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(defaultDeptId);
        })
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.$emit("change", data.id);
      this.$emit("select", data.id);
    },
    /**
     * 获取第一个叶子结点
     */
    getFirstLeafNode(root) {
      if (!root) {
        return null;
      }
      if (root.length === 0) {
        return null;
      }
      for (let element of root) {
        if (element.children && element.children.length >= 0) {
          const leafNode = this.getFirstLeafNode(element.children);
          if (leafNode) {
            return leafNode;
          }
        } else {
          return element;
        }
      }
      return null;
    },
    /**
     * 根据id获取部门信息
     */
    getDeptNameById(id, options) {
      if (!options) options = this.deptOptions
      for (let i=0;i<options.length;i++) {
        let element = options[i];
        if (element.id == id) {
          return element.label
        } else {
          if (element.children && element.children.length >= 0) {
            let label = this.getDeptNameById(id, element.children);
            if(label){
              return label;
            }
          }
        }
      }
    }
  }
}
</script>

<style>
</style>